package org.demo.xsd;

import com.sun.xml.xsom.XSElementDecl;
import com.sun.xml.xsom.XSParticle;
import com.sun.xml.xsom.XSType;
import com.sun.xml.xsom.impl.util.SchemaTreeTraverser;

/**
 * 使用访问者模式遍历 Schema 各元素
 * @author  
 * @date    2011-1-27
 * @file    org.demo.xsd.ElementVistor.java
 */
public class ElementVistor extends SchemaTreeTraverser{
	
	private final int level;
	private ElementVistor nextVistor;

	/**
	 * 构造函数
	 */
	public ElementVistor(){
		this.level = 0;
	}
	/**
	 * 构造函数
	 * @param level
	 */
	public ElementVistor(int level){
		this.level = level;		
	}
	/**
	 * for schema particle
	 */
	@Override
	public void particle(XSParticle part) {
		part.getTerm().visit(getNextVistor());
	}
	/**
	 * for xsd:element
	 */
	@Override
	public void elementDecl(XSElementDecl decl) {
	    printPadding();
	    System.out.println(decl.getName());
	    XSType type = decl.getType();
	    if (type.isComplexType()){
	    	type.visit(getNextVistor());
	    }
	}
	/**
	 * 获取下一层元素的访问者
	 * @return
	 */
	private ElementVistor getNextVistor(){
		if (nextVistor == null){
			nextVistor = new ElementVistor(level + 1);
		}
		return nextVistor;
	}
	/**
	 * 打印空格
	 * @param level
	 */
	private void printPadding(){
		for (int i=0; i<level; i++){
			System.out.print("  ");
		}
	}
}
